package com.example.memosystem.controller;

import com.example.memosystem.model.Category;
import com.example.memosystem.model.User;
import com.example.memosystem.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/category")
public class CategoryController {
    
    @Autowired
    private CategoryService categoryService;
    
    @GetMapping("/list")
    public String list(HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        List<Category> categories = categoryService.findAllByUserId(user.getId());
        model.addAttribute("categories", categories);
        return "category/list";
    }
    
    @GetMapping("/add")
    public String addPage(HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        return "category/add";
    }
    
    @PostMapping("/add")
    public String add(Category category, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        category.setUserId(user.getId());
        categoryService.addCategory(category);
        return "redirect:/category/list";
    }
    
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable Integer id, HttpSession session, Model model) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        Category category = categoryService.findById(id, user.getId());
        if (category == null) {
            return "redirect:/category/list";
        }
        
        model.addAttribute("category", category);
        return "category/edit";
    }
    
    @PostMapping("/edit")
    public String edit(Category category, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        category.setUserId(user.getId());
        categoryService.updateCategory(category);
        return "redirect:/category/list";
    }
    
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable Integer id, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        categoryService.deleteCategory(id, user.getId());
        return "redirect:/category/list";
    }
}